package com.tianxin.workbao.workBao.Activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.adapter.SelectCoalAdapter;
import com.tianxin.workbao.workBao.bean.Coal;
import com.tianxin.workbao.workBao.bean.VWashWork;
import com.tianxin.workbao.workBao.bean.WashCoaltype;
import com.tianxin.workbao.workBao.bean.WashWork;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.CoalProvide;
import com.tianxin.workbao.workBao.dataProvide.WashWorkProvide;
import com.tianxin.workbao.workBao.holder.SelectCoalHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.SPUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by hacker on 2017/7/27.
 */

public class WashWorkOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener, MyPopupWindowListener {

    private CircleImageView addInBtn;
    private CircleImageView addOutBtn;
    private LinearLayout inLinearLayout;
    private LinearLayout outLinearLayout;
    private EditText remarkET;
    private TextView inHintTv;
    private TextView outHintTv;
    private TextView numberTV;
    private TextView inWeightTV;
    private TextView outWeightTV;
    private EditText useElectricET;
    private EditText useOilET;
    private EditText useMediniceET;
    private EditText useTimeET;
    private EditText workerET;
    private EditText startTimeET;
    private EditText endTimeET;
    TextView coalNameTv;
    EditText weightET;
    TextView oldcoalNameTv;
    EditText oldWeightET;
    private FloatingActionButton saveFab;

    private VWashWork mVWashWork;
    private CoalProvide coalProvide;
    private WashWorkProvide washWorkProvide;
    private List<WashCoaltype> mInCoalList;
    private List<WashCoaltype> mOutCoalList;
    private List<Coal> mCoalList;
    private PopupWindow popupWindow;
    private float totalInWeight = 0;
    private float totalOutWeight = 0;
    private final int POPUP_TYPE_COAL = 0;
    private int currType;
    private WashCoaltype currWashCoaltype;
    private WashWork washWork;
    private String number;
    private boolean startTimeEnable;
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private boolean isSelectDate;
    private int lastcoalID;
    private SimpleDateFormat sdf;
    private Float beforeChangedValue;
    private boolean isCanNext = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wash_option);

        initView();
        initData();
        initEvent();
        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setTitle("生产数据录入");
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        setSupportActionBar(mToolbar);
        saveFab = findViewById(R.id.save_fab);
        addInBtn = findViewById(R.id.in_add_btn);
        addOutBtn = findViewById(R.id.out_add_btn);
        inLinearLayout = findViewById(R.id.in_coal_linearLayout);
        outLinearLayout = findViewById(R.id.out_coal_linearLayout);
        inHintTv = findViewById(R.id.in_hint);
        outHintTv = findViewById(R.id.out_hint);
        numberTV = findViewById(R.id.number);
        inWeightTV = findViewById(R.id.in_weight);
        outWeightTV = findViewById(R.id.out_weight);
        useElectricET = findViewById(R.id.use_electric);
        useOilET = findViewById(R.id.use_oil);
        useMediniceET = findViewById(R.id.use_medicine);
        useTimeET = findViewById(R.id.use_time);
        workerET = findViewById(R.id.workers);
        startTimeET = findViewById(R.id.start_time);
        endTimeET = findViewById(R.id.end_time);
        remarkET = findViewById(R.id.remark);
    }

    @Override
    public void initData() {
        mVWashWork = new VWashWork();
        washWork = new WashWork();
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        number = BeansUtil.getNumber(Constant.WAS_WORK_HEADER);
        washWork.setNumber(number);
        washWork.setAddtime(new Date());
        washWork.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        washWork.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));

        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }


    @Override
    public void initEvent() {
        mToolbar.setNavigationOnClickListener(view -> WashWorkOptionActivity.this.finish());
        saveFab.setOnClickListener(this);
        addInBtn.setOnClickListener(this);
        addOutBtn.setOnClickListener(this);
        startTimeET.setOnClickListener(this);
        endTimeET.setOnClickListener(this);
    }

    @Override
    public void bindView() {
        numberTV.setText(number);
    }

    //View.OnClickListener
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //save to server and local db
            case R.id.save_fab:
                save();
                break;
            case R.id.in_add_btn:
                currType = WashCoaltype.TYPE_IN;
                addView();
                break;
            case R.id.out_add_btn:
                currType = WashCoaltype.TYPE_OUT;
                addView();
                break;
            case R.id.start_time:
                startTimeEnable = true;
                showPickerDialog();
                break;
            case R.id.end_time:
                startTimeEnable = false;
                showPickerDialog();
                break;
        }
    }

    /**
     * show date Picker dialog
     */
    private void showPickerDialog() {
        isSelectDate = true;
        DatePickerDialog datePickerDialog =
                new DatePickerDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK, dateListener, year, month, day);
        datePickerDialog.show();
    }

    /**
     * show time Picker dialog
     */
    private void showSelectTimeDialog() {
        isSelectDate = false;
        TimePickerDialog tpd =
                new TimePickerDialog(this, timeListener, hour, minute, DateFormat.is24HourFormat(this));
        tpd.show();

    }

    private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int y, int monthOfYear, int dayOfMonth) {
            year = y;
            month = monthOfYear;
            day = dayOfMonth;
            updateDate();
            showSelectTimeDialog();
        }

    };

    private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int h, int m) {
            hour = h;
            minute = m;
            updateDate();
        }
    };

    private void updateDate() {
        String m = null, d = null, min = null, h = null, s = "00";
        if (startTimeEnable == true) {
            if (isSelectDate == true) {
                startTimeET.setText("");
                if (month + 1 < 10) {
                    m = "0" + (month + 1);
                } else {
                    m = (month + 1) + "";
                }
                if (day < 10) {
                    d = "0" + day;
                } else {
                    d = day + "";
                }
                startTimeET.setText(year + "-" + m + "-" + d);
            } else {
                String temp = startTimeET.getText() + " ";
                if (hour < 10) {
                    h = "0" + hour;
                } else {
                    h = hour + "";
                }
                if (minute < 10) {
                    min = "0" + minute;
                } else {
                    min = minute + "";
                }
                startTimeET.setText(temp + h + ":" + min + ":" + s);
            }
        } else {
            if (isSelectDate == true) {
                endTimeET.setText("");
                if (month + 1 < 10) {
                    m = "0" + (month + 1);
                } else {
                    m = (month + 1) + "";
                }
                if (day < 10) {
                    d = "0" + day;
                } else {
                    d = day + "";
                }
                endTimeET.setText(year + "-" + m + "-" + d);
            } else {
                String temp = endTimeET.getText() + " ";
                if (hour < 10) {
                    h = "0" + hour;
                } else {
                    h = hour + "";
                }
                if (minute < 10) {
                    min = "0" + minute;
                } else {
                    min = minute + "";
                }
                endTimeET.setText(temp + h + ":" + min + ":" + s);
            }
        }
    }


    private void addView() {
        beforeChangedValue = Float.valueOf(0);
        currWashCoaltype = null;
        if (isCanNext == false) {
            showMessage("上一次添的煤种信息录入不完整");
            return;
        }
        View view = getLayoutInflater().inflate(R.layout.wash_coaltype_add_view, null, false);
        if (oldcoalNameTv != null) {
            oldcoalNameTv.setOnClickListener(null);
        }
        if (oldWeightET != null) {
            oldWeightET.addTextChangedListener(null);
            oldWeightET.setEnabled(false);
        }

        coalNameTv = view.findViewById(R.id.coal_name);
        weightET = view.findViewById(R.id.weight);
        weightET.setFocusable(true);
        coalNameTv.setOnClickListener(view1 -> {
            if (currWashCoaltype != null) {
                showMessage("上一次添的煤种信息录入不完整!");
                return;
            } else {
                getCoalList();
                isCanNext = true;
            }
        });
        weightET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().length() > 0) {
                    beforeChangedValue = Float.valueOf(charSequence.toString());
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() < 1) {
                    return;
                }
                currWashCoaltype.setTonnage(Float.valueOf(editable.toString()));
                if (currType == WashCoaltype.TYPE_IN) {
                    if (mInCoalList == null) {
                        mInCoalList = new ArrayList<>();
                    }
                    if (mInCoalList.contains(currWashCoaltype)) {
                        mInCoalList.remove(currWashCoaltype);
                    }
                    mInCoalList.add(currWashCoaltype);
                    totalInWeight += currWashCoaltype.getTonnage();
                    totalInWeight -= beforeChangedValue;
                    inWeightTV.setText(totalInWeight + "");

                } else if (currType == WashCoaltype.TYPE_OUT) {
                    if (mOutCoalList == null) {
                        mOutCoalList = new ArrayList<>();
                    }
                    if (mOutCoalList.contains(currWashCoaltype)) {
                        mOutCoalList.remove(currWashCoaltype);
                    }
                    mOutCoalList.add(currWashCoaltype);
                    totalOutWeight += currWashCoaltype.getTonnage();
                    totalOutWeight -= beforeChangedValue;
                    outWeightTV.setText(totalOutWeight + "");
                }
            }
        });
        weightET.setOnFocusChangeListener((view12, b) -> {
            if (b) {

            } else {
                if (weightET.getText().length() > 0) {
                    currWashCoaltype = null;
                    isCanNext = true;
                } else {
                    showMessage("请输入该煤种的吨位");
                    weightET.setFocusable(true);
                }
            }
        });
        if (currType == WashCoaltype.TYPE_IN) {
            inLinearLayout.addView(view);
            inHintTv.setVisibility(View.GONE);
        } else {
            outLinearLayout.addView(view);
            outHintTv.setVisibility(View.GONE);
        }
        oldcoalNameTv = coalNameTv;
        oldWeightET = weightET;
        isCanNext = false;
    }

    /**
     * save the sampling
     */
    private void save() {
        if (mVWashWork == null) {
            showMessage("数据异常");
            return;
        }
        if (mInCoalList == null || mInCoalList.isEmpty()) {
            showMessage("未增加入洗煤种");
            onRestart();
            return;
        }
        if (mOutCoalList == null || mOutCoalList.isEmpty()) {
            showMessage("未增加产出煤种");
            onRestart();
            return;
        }
        if (totalInWeight <= 0) {
            showMessage("入洗煤种的吨数出误");
            return;
        }
        washWork.setIntotal(totalInWeight);
        if (totalOutWeight <= 0) {
            showMessage("产出煤种的吨数出误");
            return;
        }
        washWork.setOuttotal(totalOutWeight);
        try {
            washWork.setUseelectric(Float.valueOf(useElectricET.getText().toString()));
        } catch (Exception e) {
            showMessage("用电输入错误");
            useElectricET.setText("");
            useElectricET.setFocusable(true);
            return;
        }
        try {
            washWork.setUseoil(Float.valueOf(useOilET.getText().toString()));
        } catch (Exception e) {
            showMessage("用油输入错误");
            useOilET.setText("");
            useOilET.setFocusable(true);
            return;
        }
        try {
            washWork.setUsemedecine(Float.valueOf(useMediniceET.getText().toString()));
        } catch (Exception e) {
            showMessage("用药输入错误");
            useMediniceET.setText("");
            useMediniceET.setFocusable(true);
            return;
        }
        try {
            washWork.setUsetime(Float.valueOf(useTimeET.getText().toString()));
        } catch (Exception e) {
            showMessage("用时输入错误");
            useTimeET.setText("");
            useTimeET.setFocusable(true);
            return;
        }
        if (startTimeET.getText().toString().length() > 0) {
            try {
                washWork.setStarttime(sdf.parse(startTimeET.getText().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            startTimeET.setText("");
            return;
        }
        if (endTimeET.getText().toString().length() > 0) {
            try {
                washWork.setEndtime(sdf.parse(endTimeET.getText().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            endTimeET.setText("");
            return;
        }
        washWork.setWorkers(Integer.valueOf(workerET.getText().toString()));

        washWork.setRemark(remarkET.getText().toString());
        mVWashWork.setWashWork(washWork);
        mVWashWork.setInWashCoaltypes(mInCoalList);
        mVWashWork.setOutWashCoaltypes(mOutCoalList);
        // save
        getWashWorkProvide().save(mVWashWork);
    }

    private void getCoalList() {
        getCoalProvide().getAllCoals();
    }


    @Override
    public void OnMyClick(Integer selectType, Integer id, String information) {

        switch (selectType) {
            case Constant.SELECT_TYPE_COAL:
                dismissPoPup();
                if (lastcoalID == id) {
                    showMessage("相同的煤种不能选择两次");
                    return;
                }
                lastcoalID = id;
                currWashCoaltype = new WashCoaltype();
                currWashCoaltype.setCoaltypeid(id);
                currWashCoaltype.setCoaltype(information);
                coalNameTv.setText(information);
                break;
        }
    }

    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            this.finish();
        } else if (msg.contains("failure")) {
            Toast.makeText(this, "录入失败！\n " + msg.substring(msg.indexOf("failure") + 1, msg.length()), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 2000);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List) {
            if (((List) result).size() > 0) {
                if (((List) result).get(0) instanceof Coal) {
                    mCoalList = (List<Coal>) result;
                    if (mCoalList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_COAL);
                    }
                }
            }
        } else {
            showMessage("response other information");
        }
    }

    private void showSelectPopup(int type) {
        popupWindow = new PopupWindow();
        switch (type) {
            case POPUP_TYPE_COAL:
                SelectCoalAdapter selectCoalAdapter = new SelectCoalAdapter(mCoalList, this, this);
                SelectCoalHolder selectCoalHolder = new SelectCoalHolder(this, this, selectCoalAdapter);
                popupWindow.setContentView(selectCoalHolder.getContentView());
                popupWindow.setHeight(340);
                break;
            default:
                return;
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.write)));
        popupWindow.setAnimationStyle(R.style.my_popup_animation_style);
        popupWindow.showAtLocation(mToolbar, Gravity.TOP, 0, 0);
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    public CoalProvide getCoalProvide() {
        if (coalProvide == null) {
            coalProvide = new CoalProvide(this, this);
        }
        return coalProvide;
    }

    public WashWorkProvide getWashWorkProvide() {
        washWorkProvide = new WashWorkProvide(this, this);
        return washWorkProvide;
    }


    private void dismissPoPup() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    private void resertSelectData() {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }
}
